package com.joinval.common.utils;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
/**
 * @author shen shuai
 * @create 2024-09-27 下午 3:48
 */
public class RSAKeyPairGenerator {

    private static final String ALGORITHM = "RSA";
    private static final int KEY_SIZE = 1024;

    private final KeyPair keyPair;

    public RSAKeyPairGenerator() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        keyPair = keyPairGenerator.generateKeyPair();
    }

    public PublicKey getPublicKey() {
        return keyPair.getPublic();
    }

    public PrivateKey getPrivateKey() {
        return keyPair.getPrivate();
    }

    // 将公钥转换为Base64编码的字符串
    public String getPublicKeyAsString() {
        return Base64.getEncoder().encodeToString(getPublicKey().getEncoded());
    }

    // 将私钥转换为Base64编码的字符串
    public String getPrivateKeyAsString() {
        return Base64.getEncoder().encodeToString(getPrivateKey().getEncoded());
    }

}
